package cn.cs.service.impl;

import cn.cs.client.*;
import cn.cs.common.*;
import cn.cs.pojo.*;
import cn.cs.service.RepairUserService;
import cn.cs.vo.TokenVO;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RepairUserServiceImpl implements RepairUserService{
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RestRepairUserClient repairUserClient;
    @Resource
    private RestRepOrderClient restRepOrderClient;

    @Resource
    private RestFaultTypeClient faultTypeClient;

    @Resource
    private AgentClient agentClient;

    @Resource
    private RestAppOrderClient appOrderClient;


    @Override
    public Dto doLogin(HttpServletRequest request) {
        String phone = request.getParameter("phone");
        String yzCode = request.getParameter("yzCode");
        if(EmptyUtils.isEmpty(redisUtils.get(phone))){
            return  DtoUtil.returnFail("验证码已失效","002");
        }
        if(!yzCode.equals(redisUtils.get(phone))){
            return  DtoUtil.returnFail("输入验证码有误","002");
        }
        RepairUser user = null;
        if(EmptyUtils.isNotEmpty(phone)){
            user = repairUserClient.getRepairUserByPhone(phone);
        }
        if (EmptyUtils.isNotEmpty(user)) {
            user.setDevoCode(request.getHeader("code"));
            String token = repairUserClient.createToken(request.getHeader("agent"), user);
            repairUserClient.saveToken(token, user);
            //返回TokenVO
            TokenVO tokenVO = new TokenVO(token,
                    Calendar.getInstance().getTimeInMillis() + 2*60*60 * 1000,//2h有效期
                    Calendar.getInstance().getTimeInMillis());

            return DtoUtil.returnDataSuccess(tokenVO);
        } else {
            return DtoUtil.returnFail("手机号不存在", "002");
        }
    }

    @Override
    public Dto register(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        if(EmptyUtils.isEmpty(token)){
                    String yzCode = request.getParameter("yzCode");
            String phone = request.getParameter("phone");
        if(EmptyUtils.isEmpty( redisUtils.get(phone))){
            return  DtoUtil.returnFail("验证码已经失效","002");
        }
        if(!yzCode.equals(redisUtils.get(phone))){
            return  DtoUtil.returnFail("输入验证码有误","002");
        }
        if(EmptyUtils.isNotEmpty(phone)){
            RepairUser repairUser = repairUserClient.getRepairUserByPhone(phone);
        if(EmptyUtils.isNotEmpty(repairUser)){
            return  DtoUtil.returnFail("此手机号已经存在，请换一个手机号注册","002");
        }
        }
            RepairUser user = new RepairUser();
            String id  = IdWorker.getId();
            user.setId(id);
            String invitationCode = request.getParameter("invitationCode");
            if(EmptyUtils.isNotEmpty(invitationCode)){
                user.setInvitationCode(invitationCode);
            }
            else{
                user.setInvitationCode("");
            }
            String faultType = request.getParameter("faultType");
            if(EmptyUtils.isNotEmpty(faultType)){
                String[] types = faultType.split(",");
                Map<String,Object> param =new HashMap<String, Object>();
                param.put("types",types);
                List<Map<String,Object>> cerfList = repairUserClient.getCerListByTypes(param);
                if(EmptyUtils.isNotEmpty(cerfList)){
//                List<Map<String,Object>> imgs = repairUserMapper.getRepairCerfImgs(user.getId());
//                    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
//                            request.getSession().getServletContext());
//                    // 判断是否有文件上传
                    MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
                    multipRequest.setCharacterEncoding("utf-8");
                    Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
                    int n=0;
                    for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                        n++;
                        if(n>3){
                            UploadInfo info =   UploadUtil.uploadFile(entity.getValue(),"user/repairUserCertificate/"+user.getId());
                            RepairCertificateImg repImg = new RepairCertificateImg();
                            repImg.setId(IdWorker.getId());
                            repImg.setRep_user_id(user.getId());
                            repImg.setImage_url("https://www.zzzsyh.com/image/user/repairUserCertificate/"+user.getId()+"/"+info.getOldName());
                            repImg.setCertificate_type(entity.getKey());
                            repImg.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
                            repImg.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
                            repairUserClient.insertRepairCertificateImg(repImg);
                        }
                    }
                    if(n == 3){
                        Dto dto=new Dto();
                        dto.setData(cerfList);
                        dto.setErrorCode("005");
                        dto.setMsg("您选择的服务范围需要上传您本人的技能证件");
                        dto.setSuccess("true");
                        return  dto;
                    }
                    if(n == 0){
                        return DtoUtil.returnFail("没有上传任何照片","002");
                    }
                }
                user.setFaultType(faultType);
            }

            String val = "";
            Random random = new Random();
            //参数length，表示生成几位随机数
            for (int i = 0; i < 10; i++) {
                String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
                //输出字母还是数字
                if ("char".equalsIgnoreCase(charOrNum)) {
                    //输出是大写字母还是小写字母
                    int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                    val += (char) (random.nextInt(26) + temp);
                } else if ("num".equalsIgnoreCase(charOrNum)) {
                    val += String.valueOf(random.nextInt(10));
                }
            }

            String area = request.getParameter("area");

            String idCard = request.getParameter("idCard");
            String name  = request.getParameter("name");
            if(EmptyUtils.isNotEmpty(idCard)){
                int n = repairUserClient.checkIdCardNum(idCard);
                if(n>0){
                    return DtoUtil.returnFail("此身份证已经注册过本APP，请换一个身份证","002");
                }
                MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
                multipRequest.setCharacterEncoding("utf-8");
                Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
                int m=0;
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    m++;
                    if(m<4){
                        UploadInfo info =   UploadUtil.uploadFile(entity.getValue(),"user/repIdCardImg/"+user.getId());
                        if(m == 3){
                            String picUrl ="https://www.zzzsyh.com/image/user/repIdCardImg/"+user.getId()+"/"+info.getOldName();
                            user.setHandHeldIdUrl(picUrl);
                        }
                    }
                }
                user.setId_card_no(idCard);
                user.setPersonName(name);
            }
            user.setWorkstate("0");
            user.setPassword(MD5.getMd5("123456",32));
            user.setPhone(phone);
            user.setNickname(val);
            user.setOrderNumber(0);
            user.setFaultType(faultType);
            user.setStarEvaluate("5");
            user.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            repairUserClient.insertRepairUser(user);
            //批量新增维修工接单区域
            String areas[] = area.split(",");
            List<RepairUserArea> list = new ArrayList<RepairUserArea>();
            for(String a:areas){
                Map<String, Object> map = new HashMap<String,Object>();
                RepairUserArea repairUserArea =new RepairUserArea();
                repairUserArea.setId(IdWorker.getId());
                repairUserArea.setArea(a);
                repairUserArea.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                repairUserArea.setRepair_user_id(id);
                list.add(repairUserArea);
            }
//            repairUserMapper.insertRepairUserAreaList(list);
        }else{
            RepairUser user = JSON.parseObject(redisUtils.get(token)+"", RepairUser.class);
            String faultType = request.getParameter("faultType");
            if(EmptyUtils.isNotEmpty(faultType)){
                String[] types = faultType.split(",");
                Map<String,Object> param =new HashMap<String, Object>();
                param.put("types",types);
//                List<Map<String,Object>> cerfList = repairUserMapper.getCerListByTypes(param);
                List<Map<String,Object>> cerfList = null;
                if(EmptyUtils.isNotEmpty(cerfList)){
//                    // 判断是否有文件上传
                    MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
                    multipRequest.setCharacterEncoding("utf-8");
                    Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
                    int n=0;
                    for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                        n++;
                        if(n>3){
                            UploadInfo info =   UploadUtil.uploadFile(entity.getValue(),"user/repairUserCertificate/"+user.getId());
                            Map<String,Object> repImg = new HashMap<String, Object>();
                            repImg.put("id",IdWorker.getId());
                            repImg.put("rep_user_id",user.getId());
                            repImg.put("image_url","https://www.zzzsyh.com/image/user/repairUserCertificate/"+user.getId()+"/"+info.getOldName());
                            repImg.put("certificate_type",entity.getKey());
                            repImg.put("update_time",DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
                            repImg.put("create_time",DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
//                            repairUserMapper.insertRepairCertificateImg(repImg);
                        }
                    }
                    if(n == 3){
                        Dto dto=new Dto();
                        dto.setData(cerfList);
                        dto.setErrorCode("005");
                        dto.setMsg("您选择的服务范围需要上传您本人的技能证件");
                        dto.setSuccess("true");
                        return  dto;
                    }
                    if(n == 0){
                        return DtoUtil.returnFail("没有上传任何照片","002");
                    }
                }
                user.setFaultType(faultType);
            }

            String val = "";
            Random random = new Random();
            //参数length，表示生成几位随机数
            for (int i = 0; i < 10; i++) {
                String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
                //输出字母还是数字
                if ("char".equalsIgnoreCase(charOrNum)) {
                    //输出是大写字母还是小写字母
                    int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                    val += (char) (random.nextInt(26) + temp);
                } else if ("num".equalsIgnoreCase(charOrNum)) {
                    val += String.valueOf(random.nextInt(10));
                }
            }
            String area = request.getParameter("area");
            String idCard = request.getParameter("idCard");
            String name  = request.getParameter("name");
            if(EmptyUtils.isNotEmpty(idCard)){
//                int n = repairUserMapper.checkIdCardNum(idCard);
                int n = 0;
                if(n>0){
                    return DtoUtil.returnFail("此身份证已经注册过本APP，请换一个身份证","002");
                }
                MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
                multipRequest.setCharacterEncoding("utf-8");
                Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
                int m=0;
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    m++;
                    if(m<4){
                        UploadInfo info =   UploadUtil.uploadFile(entity.getValue(),"user/repIdCardImg/"+user.getId());
                        if(m == 3){
                            String picUrl ="https://www.zzzsyh.com/image/user/repIdCardImg/"+user.getId()+"/"+info.getOldName();
                            user.setHandHeldIdUrl(picUrl);
                        }
                    }
                }
                user.setId_card_no(idCard);
                user.setPersonName(name);
            }
            user.setWorkstate("0");
            user.setPassword(MD5.getMd5("123456",32));
            user.setNickname(val);
            user.setOrderNumber(0);
            user.setFaultType(faultType);
            user.setStarEvaluate("5");
            user.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
//            repairUserMapper.updateRepairUser(user);
            //批量新增维修工接单区域
            String areas[] = area.split(",");
            List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
            for(String a:areas){
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", IdWorker.getId());
                map.put("repair_user_id", user.getId());
                map.put("area", a);
                map.put("create_time", new Date());
                list.add(map);
            }
//            repairUserMapper.insertRepairUserAreaList(list);
        }
        return DtoUtil.returnSuccess("注册成功");
    }

    @Override
    public Dto updateRepUser(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        if(user!=null){
            RepairUser newUser = new RepairUser();
            newUser.setId(user.getId());
            String password = request.getParameter("password");
            String account = request.getParameter("account");
            String name = request.getParameter("nickName");
            String area = request.getParameter("area");
            String faultType = request.getParameter("faultType");
            String id_card_no = request.getParameter("id_card_no");
            if(EmptyUtils.isNotEmpty(faultType)){
                String[] types = faultType.split(",");
                Map<String,Object> param =new HashMap<String, Object>();
                param.put("types",types);
                List<Map<String,Object>> cerfList = repairUserClient.getCerListByTypes(param);
                if(EmptyUtils.isNotEmpty(cerfList)){
                    List<RepairCertificateImg> imgs = repairUserClient.getRepairCerfImgs(user.getId());
                    boolean flage = true;
                    if(EmptyUtils.isNotEmpty(imgs)){
                        if(cerfList.size() != imgs.size()){
                            flage = false;
                        }
                    }else{
                        flage = false;
                    }
                    if(flage == false){
                        Dto dto=new Dto();
                        dto.setData(cerfList);
                        dto.setErrorCode("005");
                        dto.setMsg("您选择的服务范围需要上传您本人的技能证件");
                        dto.setSuccess("true");
                        return  dto;
                    }
                }
                newUser.setFaultType(faultType);
            }
            if(EmptyUtils.isNotEmpty(password)){
                newUser.setPassword(password);
            }
            if(EmptyUtils.isNotEmpty(name)){
                newUser.setNickname(name);
            }
            if(EmptyUtils.isNotEmpty(account)){
                newUser.setAccount(account);
            }
            if(EmptyUtils.isNotEmpty(area)){
//                user.setArea(area);
                repairUserClient.deleteRepairAreaById(newUser.getId());
                String[] areas = area.split(",");
                for(String s:areas){
                    Map<String,Object> map =new HashMap<String, Object>();
                    RepairUserArea repairUserArea = new RepairUserArea();
                    repairUserArea.setId(IdWorker.getId());
                    repairUserArea.setRepair_user_id(newUser.getId());
                    repairUserArea.setArea(s);
                    repairUserArea.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                    repairUserClient.insertRepAreas(repairUserArea);
                }
            }

            if(EmptyUtils.isNotEmpty(id_card_no)){
                newUser.setId_card_no(id_card_no);
            }
            repairUserClient.updateRepairUser(newUser);
            RepairUser retUser = repairUserClient.getRepairUserByPhone(user.getPhone());
            return DtoUtil.returnDataSuccess(retUser);
        }else{
            return DtoUtil.returnFail("不存在此用户","002");
        }
    }

    @Override
    public Dto checkPhone(HttpServletRequest request) {
        String yzCode = request.getParameter("yzCode");
        String phone = request.getParameter("phone");
        String invitationCode = request.getParameter("invitationCode");
        if(EmptyUtils.isNotEmpty(invitationCode)){
            int n = repairUserClient.checkInvitationCode(invitationCode);
            if(n == 0){
                return   DtoUtil.returnFail("邀请码错误","002");
            }
        }
        if(EmptyUtils.isEmpty( redisUtils.get(phone))){
            return  DtoUtil.returnFail("验证码已经失效或未找到","002");
        }
        if(!yzCode.equals(redisUtils.get(phone))){
            return  DtoUtil.returnFail("输入验证码有误","002");
        }
        if(EmptyUtils.isNotEmpty(phone)){
            RepairUser user = repairUserClient.getRepairUserByPhone(phone);
            if(EmptyUtils.isNotEmpty(user)){
                return  DtoUtil.returnFail("此手机号已经存在，请换一个手机号注册","002");
            }else{
                return DtoUtil.returnSuccess();
            }
        }else{
            return  DtoUtil.returnFail("手机号为空","002");
        }
    }

    @Override
    public Dto showFaultType(HttpServletRequest request) {
        List<Map<String,Object>> list = restRepOrderClient .getServiceType();
        if(EmptyUtils.isNotEmpty(list)){
            for(Map<String,Object> m:list){
                List<Map<String,Object>> children =   restRepOrderClient.getFaultType(m.get("id").toString());
                m.put("second",children);
            }
            return DtoUtil.returnDataSuccess(list);
        }else{
            return DtoUtil.returnFail("没有找到","002");
        }

    }

    @Override
    public Dto getMyInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        RepairUser newUser = repairUserClient.getRepairUserByPhone(user.getPhone());
        if(EmptyUtils.isNotEmpty(newUser)){
            return  DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("没有找到此用户","002");
        }
    }

    @Override
    public Dto changeWorkState(HttpServletRequest request, String state) throws  Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        RepairUser newUser= new RepairUser();
        newUser.setId(user.getId());
        newUser.setWorkstate(state);
        int n = repairUserClient.updateRepairUser(newUser);
        if(n>0){
            return  DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("更改失败","002");
        }
    }

    @Override
    public Dto updateRepUserPhone(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        String phone = request.getParameter("phone");
        String yzCode = request.getParameter("yzCode");
        int n = 0;
        if(EmptyUtils.isNotEmpty(phone) && EmptyUtils.isNotEmpty(yzCode) ){
            if(yzCode.equals(redisUtils.get(phone))){
                RepairUser userMap = repairUserClient.getRepairUserByPhone(phone);
                if(EmptyUtils.isNotEmpty(userMap)){
                    return  DtoUtil.returnFail("此手机号已经存在，不能更换为此手机号","002");
                }
                RepairUser newUser = repairUserClient.getRepairUserByPhone(user.getPhone());
                newUser.setPhone(phone);
                n= repairUserClient.updateRepairUser(newUser);
                if(n>0){
                    return  DtoUtil.returnSuccess();
                }else{
                    return  DtoUtil.returnFail("更换手机号失败","002");
                }
            }else{
                return  DtoUtil.returnFail("验证码不正确","002");
            }
        }else{
            return  DtoUtil.returnFail("手机号或验证码为空","002");
        }
    }

    @Override
    public Dto getMypriLci(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
            List<ClientUser> list  =    repairUserClient.getMypriLciById(user.getId());
            if(!EmptyUtils.isEmpty(list)){
                return    DtoUtil.returnDataSuccess(list);
            }else{
                return  DtoUtil.returnFail("未查到私人客户","002");
            }
    }

    @Override
    public Dto complaintInfo(HttpServletRequest request) {
        String id= request.getParameter("id");
        RepairUserComplaint complaint = repairUserClient.getComplaintById(id);
        List<RepairUserComplaintNote> list = repairUserClient.getMyComplaintNodes(id);
        if(EmptyUtils.isNotEmpty(complaint)){
            complaint.setNodes(list);
            return  DtoUtil.returnDataSuccess(complaint);
        }else{
            return DtoUtil.returnFail("没有投诉","002");
        }
    }

    @Override
    public Dto myComplaint(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        List<RepairUserComplaint> list = repairUserClient.getMyComplaint(user.getId());
        if(EmptyUtils.isNotEmpty(list)){
            return  DtoUtil.returnDataSuccess(list);
        }else{
            return DtoUtil.returnFail("没有投诉","002");
        }
    }

    @Override
    public Dto updateCertificateImgs(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
        multipRequest.setCharacterEncoding("utf-8");
        Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            UploadInfo info =   UploadUtil.uploadFile(entity.getValue(),"user/repairUserCertificate/"+user.getId());
            RepairCertificateImg  repImg= new RepairCertificateImg();
            repImg.setCertificate_type(entity.getKey());
            repImg.setRep_user_id(user.getId());
            repImg.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
            repImg.setImage_url("https://www.zzzsyh.com/image/user/repairUserCertificate/"+user.getId()+"/"+info.getOldName());
            repImg.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
            String path = repairUserClient.getCerfImgPath(repImg);
            if(EmptyUtils.isNotEmpty(path)){
                String str = "/usr/local/image/"+path.substring(path.indexOf("image/")+6,path.length());
                UploadUtil.deleteServerFile(str);
                repairUserClient.updateCertificateImgs(repImg);
            }else{
                repImg.setId(IdWorker.getId());
                repImg.setUpdate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH;mm:ss"));
                repairUserClient.insertRepairCertificateImg(repImg);
            }
        }
        return DtoUtil.returnSuccess();
    }

    @Override
    public Dto getPolicy(HttpServletRequest request) {
        List<Map<String,Object>> list  =    repairUserClient.getPolicy();
        if(!EmptyUtils.isEmpty(list)){
            return    DtoUtil.returnDataSuccess(list);
        }else{
            return  DtoUtil.returnFail("未查到平台结算政策","002");
        }
    }

    @Override
    public Dto getMyEarnings(HttpServletRequest request) {
        String token= request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        String begTime = request.getParameter("begTime");
        String endTime = request.getParameter("endTime");
        Map<String,Object> map =new HashMap<String, Object>();
        if(EmptyUtils.isNotEmpty(begTime) && EmptyUtils.isNotEmpty(endTime)){
            map.put("begTime",begTime+" 00:00:00");
            map.put("endTime",endTime+" 23:59:59");
        }else{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
            String first = format.format(c.getTime());
            map.put("begTime",first+" 00:00:00");
            Calendar ca = Calendar.getInstance();
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String last = format.format(ca.getTime());
            map.put("endTime",last+" 23:59:59");
        }
        map.put("userId",user.getId());
        List<Map<String,Object>> list  =    restRepOrderClient.getMyEarningsByDay(map);
        if(EmptyUtils.isNotEmpty(list)){
            float fa= 0;
            for(Map<String,Object> syMap : list){
                fa = fa + Float.valueOf(syMap.get("earning").toString());
            }
            Map<String,Object> resData = new HashMap<String, Object>();
            BigDecimal decimalCost = new BigDecimal(fa);
            BigDecimal allMoney = decimalCost.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            resData.put("allMoney",allMoney);
            resData.put("orderList",list);
            return    DtoUtil.returnDataSuccess(resData);
                }
            else {
            return  DtoUtil.returnFail("今天没有收入！","002");
        }
    }

    @Override
    public Dto getCountMyEarnings(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        String type  = request.getParameter("type");
        String time =request.getParameter("time");
        Map<String,Object> map =new HashMap<String, Object>();
        map.put("userId",user.getId());
        map.put("type",type);
        String[] s= new String[7];
        if("day".equals(type)){
            map.put("begTime",time+" 00:00:00");
            map.put("endTime",time+" 23:59:59");
            s=new String[24];
        }
        if("mon".equals(type)){
            if(time.indexOf("-") != -1){
                time = time.substring(time.indexOf("-")+1,time.length());
            }
            String timeStr[] = DateUtil.getThisMonth(time).split(":");
            map.put("begTime",timeStr[0]+" 00:00:00");
            map.put("endTime",timeStr[1]+" 23:59:59");
            s=new String[31];
        }
        if("yea".equals(type)){
            map.put("begTime",time+"-01-01 00:00:00");
            map.put("endTime",time+"-12-31 23:59:59");
            s=new String[12];
        }
        if("wek".equals(type)){
            String timeStr[] = DateUtil.getThisWeek(time).split(":");
            map.put("begTime",timeStr[0]+" 00:00:00");
            map.put("endTime",timeStr[1]+" 23:59:59");
        }

        List<Map<String,Object>> earns = restRepOrderClient.getCountMyEarnings(map);
        Map<String,Object> earn = new HashMap<String, Object>();
        if("wek".equals(type)){
            double yi = 0.00; double er = 0.00; double san = 0.00; double si = 0.00; double wu = 0.00; double liu = 0.00; double ri = 0.00;
            for(Map<String,Object> m:earns){
                if("Monday".equals(m.get("pay_time").toString())){
                    yi = yi + Double.valueOf(m.get("earning").toString());
                }
                if("Tuesday".equals(m.get("pay_time").toString())){
                    er = er + Double.valueOf(m.get("earning").toString());
                }
                if("Wednesday".equals(m.get("pay_time").toString())){
                    san = san + Double.valueOf(m.get("earning").toString());
                }
                if("Thursday".equals(m.get("pay_time").toString())){
                    si = si + Double.valueOf(m.get("earning").toString());
                }
                if("Friday".equals(m.get("pay_time").toString())){
                    wu = wu + Double.valueOf(m.get("earning").toString());
                }
                if("Saturday".equals(m.get("pay_time").toString())){
                    liu = liu + Double.valueOf(m.get("earning").toString());
                }
                if("Sunday".equals(m.get("pay_time").toString())){
                    ri = ri + Double.valueOf(m.get("earning").toString());
                }
            }
            BigDecimal decimalyi = new BigDecimal(yi);
            BigDecimal bigYi = decimalyi.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimaler = new BigDecimal(er);
            BigDecimal bigEr = decimaler.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimalsan = new BigDecimal(san);
            BigDecimal bigSan = decimalsan.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimalsi = new BigDecimal(si);
            BigDecimal bigSi = decimalsi.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimalwu = new BigDecimal(wu);
            BigDecimal bigWu = decimalwu.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimalliu = new BigDecimal(liu);
            BigDecimal bigLiu = decimalliu.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            BigDecimal decimalri = new BigDecimal(ri);
            BigDecimal bigRi = decimalri.setScale(2,BigDecimal.ROUND_HALF_DOWN);
            earn.put("01",String.valueOf(bigYi));earn.put("02",String.valueOf(bigEr));earn.put("03",String.valueOf(bigSan));earn.put("04",String.valueOf(bigSi));earn.put("05",String.valueOf(bigWu));earn.put("06",String.valueOf(bigLiu));earn.put("07",String.valueOf(bigRi));
            s[0] = String.valueOf(bigYi);
            s[1] = String.valueOf(bigEr);
            s[2] = String.valueOf(bigSan);
            s[3] = String.valueOf(bigSi);
            s[4] = String.valueOf(bigWu);
            s[5] = String.valueOf(bigLiu);
            s[6] = String.valueOf(bigRi);
        }else{
            for(int n=0;n<s.length;n++){
                for(Map<String,Object> m:earns){
                    if(String.valueOf(n+1).equals(m.get("pay_time").toString())){
                        s[n]=m.get("earning").toString();
                    }
                }
                if(EmptyUtils.isEmpty(s[n])){
                    s[n] = "0";
                }
            }
        }
        Map<String,Object> retDataMap = new HashMap<String, Object>();
        retDataMap.put("data",s);
        if(!EmptyUtils.isEmpty(retDataMap)){
            return   DtoUtil.returnDataSuccess(retDataMap);
        }else{
            return  DtoUtil.returnFail("没有查到数据！","002");
        }
    }

    @Override
    public Dto appSettlement(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        String type= request.getParameter("type");
        RepairUser     neUser= repairUserClient.getRepairUserByPhone(user.getPhone());
        String alipay = ""; String weChart ="";
        if("1".equals(type)){
            if(EmptyUtils.isEmpty(neUser.getOpenid())){
                return  DtoUtil.returnFail("没有绑定微信账号，请先绑定后再申请","002");
            }else{
                weChart =  neUser.getOpenid();
            }
        }else{
            if(EmptyUtils.isEmpty(neUser.getAlipay_userid())){
                return  DtoUtil.returnFail("没有绑定支付宝账号，请先绑定后再申请","002");
            }else{
                alipay = neUser.getAlipay_userid();
            }
        }
        List<Map<String,Object>> types = repairUserClient.getPolicy();
        Map<String,Object> obj = types.get(0);
        String pol_date  = obj.get("pol_date").toString();//结算日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset2 = 7 - dayOfWeek;
        calendar.add(Calendar.DATE, offset2 - 7);
        String lastEndDate = format.format(calendar.getTime());
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        Map<String,Object> param = new HashMap<String, Object>();
        if(Integer.valueOf(pol_date) != w){
            return DtoUtil.returnFail("今天不是结算日，暂不能申请结算","002");
        }
        RepSettlement settlement = repairUserClient.getLastSettlement(user.getId());
        String begin_time = "";
        if(EmptyUtils.isNotEmpty(settlement)){
            String appTime = settlement.getApp_time();
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(DateUtil.parse(appTime,"yyyy-MM-dd"));
            int dayOfWeek2 = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
            int offset22 = 7 - dayOfWeek2;
            calendar1.add(Calendar.DATE, offset22 - 7);
            begin_time= format.format(calendar1.getTime());
            param.put("begTime",begin_time+" 23:59:59");
        }
        param.put("rep_user_id",user.getId());
        param.put("endTime", lastEndDate + " 23:59:59");
        List<RepOrder> orders = restRepOrderClient.getOrdersByDate(param);
        double i = 0;
        String id = IdWorker.getId();
        for(RepOrder m :orders){
            i = i+ Double.valueOf(m.getEarning());
            SettlementOrder settlementOrder = new SettlementOrder();
            settlementOrder.setRep_order_id(m.getId());
            settlementOrder.setApp_set_id(id);
            settlementOrder.setId(IdWorker.getId());
            settlementOrder.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            repairUserClient.insertSettOrder(settlementOrder);
            m.setIs_appset("1");
            restRepOrderClient.updateRepOrderIsAppset(m);
        }
        RepSettlement repSettlement = new RepSettlement();
        repSettlement.setId(id);
        repSettlement.setRep_user_id(user.getId());
        repSettlement.setApp_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        repSettlement.setApp_state("0");
        BigDecimal decimalCit = new BigDecimal(i);
        BigDecimal setCount = decimalCit.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        repSettlement.setApp_set_count(setCount.toString());
        repSettlement.setType(type);
        repSettlement.setOpenid(weChart);
        repSettlement.setAlipay_userid(alipay);
        if("".equals(begin_time)){
            repSettlement.setBegin_time("");
        }else{
            repSettlement.setBegin_time(begin_time +" 23:59:59");
        }
        repSettlement.setEnd_time(lastEndDate +" 23:59:59");
       int n =  repairUserClient.insertSett(repSettlement);
       if(n>0){
           return  DtoUtil.returnSuccess();
       }else{
           return  DtoUtil.returnFail("申请失败","002");
       }
    }

    @Override
    public Dto uploadImage(HttpServletRequest request) {
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        RepairUser newUser = new RepairUser();
        newUser.setId(user.getId());
        if(EmptyUtils.isNotEmpty(user.getImage_url())){
            String str = user.getImage_url().substring(user.getImage_url().indexOf("=")+1,user.getImage_url().length());
            UploadUtil.deleteServerFile(str);
        }
        UploadInfo info= UploadUtil.fileUpload(request,"user/repHeadImage/"+user.getId());
        if(EmptyUtils.isNotEmpty(info)){
            newUser.setImage_url("https://www.zzzsyh.com/image/user/repHeadImage/"+user.getId()+"/"+info.getOldName());
            repairUserClient.updateRepairUser(newUser);
            return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("上传失败","002");
        }

    }

    @Override
    public Dto appSetMoney(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        RepairUser user = JSON.parseObject(redisUtils.getString(token), RepairUser.class);
        List<Map<String,Object>> types = repairUserClient.getPolicy();
        Map<String,Object> obj = types.get(0);
        String pol_date  = obj.get("pol_date").toString();//结算日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset2 = 7 - dayOfWeek;
        calendar.add(Calendar.DATE, offset2 - 7);
        String lastEndDate = format.format(calendar.getTime());
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        Map<String,Object> param = new HashMap<String, Object>();
        if(Integer.valueOf(pol_date) != w){
            return DtoUtil.returnFail("今天不是结算日，暂不能申请结算","002");
        }
        RepSettlement repSettlement = repairUserClient.getLastSettlement(user.getId());
        if(EmptyUtils.isNotEmpty(repSettlement)){
            String appTime = repSettlement.getApp_time();
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(DateUtil.parse(appTime,"yyyy-MM-dd"));
            int dayOfWeek2 = calendar1.get(Calendar.DAY_OF_WEEK) - 1;
            int offset22 = 7 - dayOfWeek2;
            calendar1.add(Calendar.DATE, offset22 - 7);
            String begTime = format.format(calendar1.getTime());
            param.put("begTime",begTime+" 23:59:59");
        }
        param.put("rep_user_id",user.getId());
        param.put("endTime", lastEndDate + " 23:59:59");
        String setMoney = restRepOrderClient.getSetMoney(param);
        if(EmptyUtils.isEmpty(setMoney)){
            setMoney = "0";
        }
        return  DtoUtil.returnDataSuccess(setMoney);
    }

    @Override
    public List<Map<String, Object>> getCertificateImgByUserId(String rep_user_id) {
        return repairUserClient.getCertificateImgByUserId(rep_user_id);
    }

    @Override
    public List<Map<String, Object>> getCertificateListByFaultId(String fault_id)throws Exception {
        List<Map<String, Object>> list = repairUserClient.getCertificateListByFaultId(fault_id);
        for(Map<String, Object> a:list){
            FaultType faultType = faultTypeClient.getFaultTypeByIdOnlyOne(fault_id);
            if(EmptyUtils.isNotEmpty(fault_id)){
                a.put("fault_name", faultType.getFaultName());
                a.put("service_name", faultType.getServiceName());
            }
        }
        return list;
    }

    @Override
    public Dto registerWx(HttpServletRequest request) throws Exception {
        String yzCode = request.getParameter("yzCode");
        String phone = request.getParameter("phone");
        if(EmptyUtils.isEmpty( redisUtils.get(phone))){
            return  DtoUtil.returnFail("验证码已经失效","002");
        }
        if(!yzCode.equals(redisUtils.get(phone))){
            return  DtoUtil.returnFail("输入验证码有误","002");
        }
        if(EmptyUtils.isNotEmpty(phone)){
            int i = repairUserClient.getUserCountByPhone(phone);
            if(i>0){
                return  DtoUtil.returnFail("比号码已验证<br>请下载安装APP直接登录","003");
            }
        }
        RepairUser user = new RepairUser();
        String invitationCode = request.getParameter("invitationCode");
        if(EmptyUtils.isNotEmpty(invitationCode)){
            int n = agentClient.checkInvitationCode(invitationCode);
            if(n>0){
                user.setInvitationCode(invitationCode);
            }else{
                DtoUtil.returnFail("邀请码错误","004");
            }
        }else{
            user.setInvitationCode("");
        }
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < 10; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }

        String id  =IdWorker.getId();
        user.setId(id);
        user.setWorkstate("0");
        user.setPassword(MD5.getMd5("123456",32));
        user.setPhone(phone);
        user.setNickname(val);
        user.setOrderNumber(0);
        user.setStarEvaluate("5");
        user.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        return DtoUtil.returnSuccess("注册成功", repairUserClient.insertRepairUser(user));
    }

    @Override
    public void modifyRepairUser(RepairUser repairUser) throws Exception {
        repairUserClient.updateRepairUser(repairUser);
    }

    @Override
    public List<Map<String, Object>> getRepairUserArea(String id) {
        return repairUserClient.getRepairUserArea(id);
    }

    @Override
    public int insertCertificateList(Map<String, Object> param) {
        return repairUserClient.insertCertificateList(param);
    }

    @Override
    public int delCertificateImg(String id) {
        return repairUserClient.delCertificateImg(id);
    }

    @Override
    public Page<RepairUser> queryRepairUserPageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) {
        Integer total = repairUserClient.getRepairUserCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<RepairUser> productTypeList = repairUserClient.getRepairUserListByMap(param);
        page.setRows(productTypeList);
        return page;
    }

    @Override
    public Page<Map<String, Object>> getRepairUserDayByMap(Map<String, Object> param, Integer pageNo, Integer pageSize)throws Exception {
        Integer total = appOrderClient.getRepairUserDayByMapCount(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Map<String, Object>> list = appOrderClient.getRepairUserDayByMap(param);
        for(Map<String, Object> a:list){
            String rep_user_id = a.get("rep_user_id").toString();
            RepairUser repairUser = repairUserClient.getRepairUserById(rep_user_id);
            a.put("id", repairUser.getId());a.put("personName", repairUser.getPersonName());
            a.put("phone", repairUser.getPhone());a.put("image_url", repairUser.getImage_url());
            a.put("id_card_no", repairUser.getId_card_no());a.put("handHeldIdUrl", repairUser.getHandHeldIdUrl());
        }
        page.setRows(list);
        return page;
    }

    //获取私人维修工
    @Override
    public Dto getRepairUserByUserId(HttpServletRequest request) throws  Exception{

        String userId = request.getParameter("userId");
        Map<String, Object> map = getRepairUserByUserId(userId);
        if(map != null){
            List<ServiceType> serviceTypeList = faultTypeClient.getServiceTypeList();
            String fault_type_id = map.get("fault_type_id").toString();
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            String faultTypeIds[] = fault_type_id.split(",");
            List<String> fIds = Arrays.asList(faultTypeIds);
            for(ServiceType s:serviceTypeList){
                String sId = s.getId();
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("ids", fIds);
                param.put("parentId", sId);
                List<FaultType> faultTypeList = faultTypeClient.getFaultTypeEntityByParentId(param);
                if(faultTypeList.size() > 0){
                    Map<String, Object> sMap = new HashMap<String, Object>();
                    sMap.put("serviceName", s.getServiceName());
                    sMap.put("faultTypeList", faultTypeList);
                    list.add(sMap);
                }
            }
            map.put("serviceTypeList", list);
        }
        return DtoUtil.returnSuccess("查询成功", map);
    }

    //获取私人维修工
    @Override
    public Map<String, Object> getRepairUserByUserId(String userId) throws  Exception{
        Map<String, Object> map = repairUserClient.getRepairUserByUserId(userId);
        return map;
    }

}
